<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>拖轮电脑远控界面</title>
  <script src="../dist/slcc-browser.js"></script>
  <script src="./demo.js"></script>
  <link rel="stylesheet" type="text/css" href="./demo.css" />
  <script>
    // demo.html?address=PHSRC://xxxxxxx/;PHSRC_HTTPS://xxxxxxxx/;UsingMultiChannel://;&cid=xxxxx
    // Demo内容，通过querystring获取连接参数
    // 主机参数
    var validParameter = false;
    var query = location.search;
    var queryParams = {};
    var reg = /PHSRC_(HTTP|HTTPS):\/\/([^\/]+):(\d+)*\//;
    var host;
    var cid;
    var ssl = false;
    var port = 80;

    var queryArr = query.substring(1).split("&");

    for (var i = 0, l = queryArr.length; i < l; i++) {
      var pair = queryArr[i].split("=", 2);

      queryParams[pair[0]] = pair[1];
    }
    
    if (queryParams["deviceName"]){
      window.document.title = decodeURIComponent("远控中：" + queryParams["deviceName"]);
    }

    if (!queryParams["address"] || !queryParams["cid"]) {
      alert("Missing parameter");
    } else {
      validParameter = true;
    }

    var matches = queryParams["address"].match(reg);
    if (!matches.length || undefined === matches[1]) {
      alert("Invalid address format");
      validParameter = false;
    }

    host = matches[2];
    // 独立部署可以打开以下两行注释，会根据地址适配是否走加密
    port = matches[3];
    ssl = -1 != matches[1].indexOf("HTTPS");
    cid = queryParams["cid"];
  </script>
  <style>
    html,
    body {
      height: 100%;
      padding: 0;
      margin: 0;
      background: #000;
      text-align: center;
    }

    #wrapper {
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <!-- 此为Demo页面，更详细内容请参看SDK文档 -->
  <!-- 桌面视图的父节点 -->
  <div id="wrapper"></div>

  <div class="msg-placeholder" id="msg">
    <div class="loading" id="loading-animate">
      <span></span><span></span><span></span><span></span><span></span>
    </div>
    <span id="msg-text" class="msg-text">正在加载程序...</span>
  </div>

  <script>
    // 获取鼠标键盘事件的实例，用于终止时间监听
    var mouseHandler, keyboardHandler
    function stopControlEventHijack() {
      if (mouseHandler !== undefined)
        mouseHandler.stop()

      if (keyboardHandler !== undefined)
        keyboardHandler.stop()
    }

    var desktop = null;
    addEventListener("load", function () {
      if (validParameter) {
        // START 向日葵远程桌面
        var client = new SunloginControl.Client({
          // 客户端

          // SDK
          host: host, // FROM SDK: PHSRC://11840.slp2p-live01.oray.net:4118/;PHSRC_HTTPS://11840.slp2p-live01.oray.net:443/;UsingMultiChannel://; 只要主机名
          embed: true, // SDK 传true
          ssl: ssl, // slp2p 线上没有证书，如果是独立服务器且SSL配置齐全，可打开
          cid: cid, // FROM SDK: CID
          port: port, // 缺省443

          debug: true // 控制台日志输出，生产环境请关闭debug
        });

        updateMessage("开始连接");

        // 初始化桌面视图
        var wrapper = document.getElementById("wrapper");
        var view = new SunloginControl.DesktopView(wrapper);
        var imgInfo = null;
        

        client
          .connect() // 客户端连接开始
          .then(() => {
            // disconnect 应该放在连接成功之后监听，连接失败直接通过catch捕获
            // 否则连接过程中可能会有若干次disconnect事件
            client.on("disconnect", function () {
              wrapper.style.display = "none";
              updateMessage("连接断开", false);
              view = null;
              delete view;
            });

            // 连接桌面插件
            desktop = new SunloginControl.Plugin.Desktop({
              quality: 10
            });
            var framesCount = (totalBytes = 0);
            client.connectPlugin(desktop);

            updateMessage("连接成功，等待桌面图像");

            // imageinfo 桌面图像信息
            desktop.on("imageinfo", info => {
              view.setImageInfo(info);
            });

            desktop.on("screen", count => {
              console.log("屏幕数量：" + count);
            });

            desktop.on("session", sessions => {
              console.log("系统会话：", sessions);
            });

            // 视频数据流事件
            // DesktopView 为通用软解方案，若客户实现解码方式监听此事件
            // stream Uint8Array H264视频流
            // info object {
            //   "streamId": 10201,
            //   "width": 1920,
            //   "height": 1080,
            //   "frameId": 0,
            //   "length": 41021,
            //   "type": 0
            // }
            desktop.on("stream", (stream, info) => {
              if (view._player === undefined) setTimeout(() => {
                // 传输鼠标（触摸）& 键盘(Win)事件，不传输任何主控端事件，即为观看
                // 下面两行远程控制启动后会对document拦截输入时间，通过各自的stop()方法中止拦截和控制操作
                mouseHandler = desktop.transportMouseEvent(view._player.canvas, {
                  moveOutRelease: true
                });
                keyboardHandler = desktop.transportKeyBoardEvent(view._player.canvas);
              }, 0);

              desktop.sendDecodeFinishMessage(++framesCount)

              // framesCount++;
              // totalBytes += info.length;
              view.decode(stream, info);

              hideMessage();
              //desktop.sendFrameControlMessage(framesCount, totalBytes);
            });
          })
          .catch(e => {
            console.log("Error occured: ", e);
            updateMessage("连接失败: " + e, false);
          });

        // 页面unload关闭客户端连接
        window.onunload = function () {
          client.disconnect();
        };
      }
    });
  </script>
</body>

</html>